<?php

namespace Lib\Core;

class Api extends Request {

	protected $func;

	public function __construct() {
	    parent::__construct();
	}

	/**
	 * 设置ajax控制器调用的方法.
	 *
	 * @param  string $func 方法名称.
	 *
	 * @return $this
	 */
	public function setFunction($func) {
		$this->func = $func;
		return $this;
	}

	/**
	 * Api 控制器运行.
	 */
	public function run() {
		$function = $this->func;
		$this->actionBefore();
		$this->$function();
		$this->actionAfter();
	}

	public function response($data) {
		$data = array(
			'error' => 0,
			'data' => $data,
			'code' => 0,
            'message' => '',
		);
        $callback = $this->getParam('callback');//jsonp回调
        if($callback) {
            echo $callback.'('.json_encode($data).')';
        } else {
            echo json_encode($data);
        }
		\Main::sysExit();
	}

	public function responseError($msg, $code = 1) {
		$data = array(
			'error' => 1,
			'data' => '',
			'code' => $code,
            'message' => $msg,
		);
        $callback = $this->getParam('callback');//jsonp回调
        if($callback) {
            echo $callback.'('.json_encode($data).')';
        } else {
            echo json_encode($data);
        }
		\Main::sysExit();
	}

	/**
	 * 执行actionIndex前调用.
	 *
	 * @return void
	 */
	protected function actionBefore(){}

	/**
	 * 执行actionIndex后调用.
	 *
	 * @return void
	 */
	protected function actionAfter(){}
}